<template>
  <view class="container">
    <!-- 天气卡片 -->
    <uni-row :gutter="20">
      <uni-col :span="24">
        <uni-card shadow="0" margin="0" padding="0" class="card weather-card">
          <view class="weather-content">
            <text class="temperature">13°</text>
            <image src="/static/images/cloud-icon.png" class="icon" />
          </view>
          <view class="weather-info">
            <text class="weather-text">多云</text>
            <text class="time-text">晚间</text>
          </view>
        </uni-card>
      </uni-col>
    </uni-row>

    <!-- 设备卡片 -->
    <uni-row :gutter="20">
      <uni-col v-for="(device, index) in devices" :key="index" :span="12">
        <uni-card shadow="0" class="card device-card">
          <view class="device-content">
            <!-- 左侧：图标部分 -->
            <image src="/static/images/camera-icon.png" class="device-icon" />

            <!-- 中间：设备信息部分 -->
            <view class="device-info">
              <text class="device-name">{{ device.name }}</text>
              <text :class="['status', device.online ? 'online' : 'offline']">
                {{ device.online ? '在线' : '离线' }}
              </text>
              <text class="device-location">{{ device.location || '未设置位置' }}</text>
            </view>

            <!-- 右侧：开关部分 -->
            <switch 
              :checked="device.online" 
              @change="(e) => toggleDeviceStatus(device, index, e.detail.value)"
              class="custom-switch"
              :disabled="!device.isBound"
            />
            
            <!-- 操作按钮，只有在编辑模式下显示 -->
            <view v-if="isEditing" class="action-buttons">
              <uni-icons 
                type="compose" 
                size="20" 
                color="#32c5d2"
                @click="showEditModal(device)"
              ></uni-icons>
              <uni-icons 
                type="closeempty" 
                size="20" 
                color="red"
                @click="confirmDelete(device.id)"
              ></uni-icons>
            </view>
          </view>
        </uni-card>
      </uni-col>

      <!-- 添加更多设备的卡片 -->
      <uni-col :span="12">
        <uni-card shadow="0" margin="0" padding="0" class="card device-card add-device-card">
          <view class="add-device-content" @click="showAddModal">
            <view class="add_icon_box">
                <uni-icons class="add_icon" type="plusempty" size="30" color="#32c5d2"></uni-icons>  
            </view>
            <text class="add-text">添加更多设备</text>
          </view>
        </uni-card>
      </uni-col>
    </uni-row>

    <!-- 编辑按钮 -->
    <view class="edit-button" @click="toggleEditMode">
      <uni-button type="default" class="capsule-button">
        {{ isEditing ? '完成' : '编辑' }}
      </uni-button>
    </view>

    <!-- 添加/编辑设备模态框 -->
    <uni-popup ref="deviceModal" type="dialog">
      <uni-popup-dialog 
        :type="modalType" 
        :title="modalTitle"
        :content="modalContent"
        :before-close="true"
        @confirm="handleModalConfirm"
        @close="handleModalClose"
      >
        <view class="modal-form">
          <uni-forms ref="deviceForm" :modelValue="formData" :rules="rules">
            <uni-forms-item label="设备名称" name="name">
              <uni-easyinput v-model="formData.name" placeholder="请输入设备名称" />
            </uni-forms-item>
            <uni-forms-item label="设备位置" name="location">
              <uni-easyinput v-model="formData.location" placeholder="请输入设备位置" />
            </uni-forms-item>
            <uni-forms-item label="序列号" name="serialNumber" v-if="isAddMode">
              <uni-easyinput v-model="formData.serialNumber" placeholder="请输入设备序列号" />
            </uni-forms-item>
          </uni-forms>
        </view>
      </uni-popup-dialog>
    </uni-popup>

    <!-- 扫码绑定提示 -->
    <uni-popup ref="scanPopup" type="message">
      <uni-popup-message 
        type="info" 
        message="请扫描设备二维码完成绑定" 
        :duration="2000"
      ></uni-popup-message>
    </uni-popup>
  </view>
</template>

<script>
import { api } from "../../utils/api/devices.js";

export default {
  data() {
    return {
      devices: [],
      isEditing: false,
      formData: {
        id: '',
        name: '',
        location: '',
        serialNumber: ''
      },
      rules: {
        name: {
          rules: [{ required: true, errorMessage: '请输入设备名称' }]
        },
        location: {
          rules: [{ required: true, errorMessage: '请输入设备位置' }]
        },
        serialNumber: {
          rules: [{ required: true, errorMessage: '请输入序列号' }]
        }
      },
      modalType: 'info',
      modalTitle: '添加设备',
      modalContent: '',
      isAddMode: true,
      isLoading: false
    };
  },
  onShow() {
    this.loadDevices();
    this.loadUserInfo();
  },
  methods: {
    // 从本地存储加载用户信息
    loadUserInfo() {
      const userInfo = uni.getStorageSync('userInfo');
      if (!userInfo || !userInfo.token) {
        uni.redirectTo({ url: '/pages/login/login' });
        return null;
      }
      return userInfo;
    },
    
    // 加载设备列表
    async loadDevices() {
      if (this.isLoading) return;
      this.isLoading = true;
      
      try {
        const userInfo = this.loadUserInfo();
        if (!userInfo) return;
        
        const result = await api.getDevices(userInfo.token);
        
        if (result && result.code === 1) {
          // 确保处理的数据是数组
          const deviceList = Array.isArray(result.data) ? result.data : [];
          this.devices = deviceList.map(device => ({
            id: device.id || 0,
            name: device.deviceName || `设备 ${device.id || '未知'}`,
            online: device.status === 1,
            isBound: !!device.isBound,
            location: device.location || '未设置位置',
            serialNumber: device.serialNumber || ''
          }));
        } else {
          console.error('获取设备列表失败:', result?.msg || '未知错误');
          uni.showToast({ title: '获取设备列表失败', icon: 'none' });
          this.devices = []; // 确保设置为空数组
        }
      } catch (error) {
        console.error('加载设备失败:', error);
        uni.showToast({ 
          title: error.message || '加载设备失败', 
          icon: 'none' 
        });
        this.devices = []; // 失败时设置为空数组
      } finally {
        this.isLoading = false;
      }
    },
    
    // 扫码绑定设备
    async scanCode(deviceId = null) {
      try {
        const userInfo = this.loadUserInfo();
        if (!userInfo) return;
        
        uni.showLoading({
          title: '准备扫码...',
          mask: true
        });
        
        const scanRes = await new Promise((resolve, reject) => {
          uni.scanCode({
            onlyFromCamera: true,
            scanType: ['qrCode'],
            success: resolve,
            fail: reject
          });
        });
        
        uni.showLoading({
          title: '正在绑定...',
          mask: true
        });
        
        try {
          let slaveId;
          // 尝试解析JSON格式的二维码
          try {
            const scanResult = JSON.parse(scanRes.result);
            slaveId = scanResult.device_id || scanResult.slaveId;
          } catch (e) {
            // 如果不是JSON格式，直接使用扫描结果
            slaveId = scanRes.result;
          }
          
          if (slaveId) {
            const bindRes = await api.bindDevice(
              deviceId || slaveId, 
              userInfo.token
            );
            
            if (bindRes?.code === 1) {
              uni.hideLoading();
              uni.showToast({ 
                title: '绑定成功', 
                icon: 'success',
                duration: 2000
              });
              await this.loadDevices();
            } else {
              throw new Error(bindRes?.msg || '绑定失败');
            }
          } else {
            throw new Error('无效的二维码');
          }
        } catch (parseError) {
          console.error('二维码处理失败:', parseError);
          throw parseError;
        }
      } catch (error) {
        uni.hideLoading();
        console.error('绑定设备失败:', error);
        
        if (error.errMsg === 'scanCode:fail cancel') {
          return; // 用户取消扫码不提示
        }
        
        uni.showToast({ 
          title: error.message || '绑定失败', 
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 显示添加设备模态框
    showAddModal() {
      this.isAddMode = true;
      this.modalTitle = '添加设备';
      this.modalType = 'info';
      this.formData = {
        id: '',
        name: '',
        location: '',
        serialNumber: ''
      };
      this.$nextTick(() => {
        this.$refs.deviceModal?.open();
      });
    },
    
    // 显示编辑设备模态框
    showEditModal(device) {
      this.isAddMode = false;
      this.modalTitle = '编辑设备';
      this.modalType = 'info';
      this.formData = {
        id: device.id,
        name: device.name,
        location: device.location,
        serialNumber: device.serialNumber
      };
      this.$nextTick(() => {
        this.$refs.deviceModal?.open();
      });
    },
    
    // 处理模态框确认
    async handleModalConfirm() {
      try {
        const valid = await this.$refs.deviceForm?.validate();
        if (!valid) return;
        
        const userInfo = this.loadUserInfo();
        if (!userInfo) return;
        
        uni.showLoading({
          title: '处理中...',
          mask: true
        });
        
        if (this.isAddMode) {
          // 添加设备
          const res = await api.addDevice({
            deviceName: this.formData.name,
            location: this.formData.location,
            serialNumber: this.formData.serialNumber,
            status: 0
          }, userInfo.token);
          
          if (res?.code === 1) {
            uni.hideLoading();
            uni.showToast({ 
              title: '添加成功', 
              icon: 'success',
              duration: 1500
            });
            this.$refs.scanPopup?.open();
            setTimeout(() => {
              this.scanCode(res.data?.id);
            }, 1500);
          } else {
            throw new Error(res?.msg || '添加失败');
          }
        } else {
          // 更新设备
          const res = await api.updateDevice({
            id: this.formData.id,
            deviceName: this.formData.name,
            location: this.formData.location,
            serialNumber: this.formData.serialNumber
          }, userInfo.token);
          
          if (res?.code === 1) {
            uni.hideLoading();
            uni.showToast({ 
              title: '更新成功', 
              icon: 'success',
              duration: 1500
            });
            await this.loadDevices();
          } else {
            throw new Error(res?.msg || '更新失败');
          }
        }
        
        this.$refs.deviceModal?.close();
      } catch (error) {
        uni.hideLoading();
        console.error('操作失败:', error);
        uni.showToast({ 
          title: error.message || '操作失败', 
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 处理模态框关闭
    handleModalClose() {
      if (this.$refs.deviceForm && this.$refs.deviceForm.resetFields) {
        this.$refs.deviceForm.resetFields();
      }
      this.$refs.deviceModal?.close();
    },
    
    // 切换设备状态
    async toggleDeviceStatus(device, index) {
      if (!device.isBound) {
        uni.showToast({ title: '请先绑定设备', icon: 'none' });
        this.$set(this.devices, index, { ...device, online: device.online });
        return;
      }
      
      try {
        const userInfo = this.loadUserInfo();
        if (!userInfo) return;
        
        // 先更新UI状态
        this.$set(this.devices, index, { ...device, online: !device.online });
        
        const res = await api.updateDevice({
          id: device.id,
          deviceName: device.name,
          location: device.location,
          serialNumber: device.serialNumber,
          status: !device.online ? 1 : 0
        }, userInfo.token);
        
        if (res?.code !== 1) {
          // 恢复原始状态
          this.$set(this.devices, index, { ...device, online: device.online });
          throw new Error(res?.msg || '状态更新失败');
        }
      } catch (error) {
        console.error('更新状态失败:', error);
        uni.showToast({ 
          title: error.message || '状态更新失败', 
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 确认删除设备
    confirmDelete(deviceId) {
      uni.showModal({
        title: '确认删除',
        content: '确定要删除此设备吗？删除后将无法恢复',
        success: async (res) => {
          if (res.confirm) {
            await this.deleteDevice(deviceId);
          }
        }
      });
    },
    
    // 删除设备
    async deleteDevice(deviceId) {
      try {
        uni.showLoading({
          title: '删除中...',
          mask: true
        });
        
        const userInfo = this.loadUserInfo();
        if (!userInfo) return;
        
        const res = await api.deleteDevice(deviceId, userInfo.token);
        
        if (res?.code === 1) {
          uni.hideLoading();
          uni.showToast({ 
            title: '删除成功', 
            icon: 'success',
            duration: 1500
          });
          await this.loadDevices();
        } else {
          throw new Error(res?.msg || '删除失败');
        }
      } catch (error) {
        uni.hideLoading();
        console.error('删除设备失败:', error);
        uni.showToast({ 
          title: error.message || '删除失败', 
          icon: 'none',
          duration: 2000
        });
      }
    },
    
    // 切换编辑模式
    toggleEditMode() {
      this.isEditing = !this.isEditing;
    }
  }
};
</script>

<style lang="scss" scoped>
page {
  background: rgba(245, 246, 248, 1);
}
    
/* 主容器样式 */
.container {
  padding: 16rpx;
}

/* 通用卡片样式 */
.card {
  margin: 20rpx 20rpx;
  padding: 24rpx;
  min-height: 240rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 12rpx;
  background-color: #f8f9fa;
}
  
/* 天气卡片样式 */
.weather-card {
  min-height: 360rpx;
  color: white;
  justify-content: flex-start;
  background: rgba(36, 204, 184, 1);
  .weather-text {
    font-size: 50rpx;
    margin: 0 0 16rpx 0;
  }
  // 修改组件默认样式
  ::v-deep .uni-card {
      margin: 20rpx;
      padding: 0 16rpx;
      overflow: hidden;
      font-family: Helvetica Neue, Helvetica, PingFang SC, Hiragino Sans GB, Microsoft YaHei, SimSun, sans-serif;
      background: rgba(36, 204, 184, 1);
      flex: 1;
  }
  ::v-deep .uni-card--border {
      border: 0;
  }
  ::v-deep .uni-card--shadow {
    position: relative;
    box-shadow: 0 2rpx 16rpx 2rpx rgba(165, 165, 165, 0.0);
  }
  ::v-deep .uni-card .uni-card__content {
      padding: 20rpx;
      font-size: 28rpx;
      color: #fff !important;
      line-height: 44rpx;
  }
}

/* 天气内容布局 */
.weather-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.temperature {
  margin: 40rpx 0 106rpx 0;
  font-size: 120rpx;
  order: -1; /* 将温度放在最左边 */
}

.weather-info {
  display: flex;
  flex-direction: column;
  align-items: flex-start; /* 将天气信息靠左对齐 */
}

.icon {
  width: 48rpx;
  height: 48rpx;
  margin-left: auto; /* 将图标推到最右边 */
}

// .icon {
//   width: 48px;
//   height: 48px;
// }

// .device-icon {
//   width: 60px;
//   height: 60px;
// }

/* 设备卡片样式 */
.device-card {
  border-radius: 16rpx;
  background-color: #fff;
  box-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.1);
  position: relative;
}

/* 设备内容布局 */
.device-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12rpx;
}

/* 设备图标样式 */
.device-icon {
  width: 60rpx;
  height: 60rpx;
  border-radius: 50%;
  position: absolute;
  top: -70rpx;
  left: 0rpx;
}

/* 设备信息部分 */
.device-info {
  margin-top: 20rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  position: absolute;
  left: 0;
  top: 50%;
}

.device-name {
  width: 130rpx;
  height: 44rpx;
  margin-bottom: 4rpx;
  font-size: 32rpx;
  color: #333;
  font-weight: bold;
}

.device-location {
  font-size: 24rpx;
  color: #999;
  margin-top: 4rpx;
}

/* 状态样式 */
.status {
  font-size: 22rpx;
  color: #999;
}

.status.online {
  color: #4caf50;
  font-size: 28rpx; 
}

.status.offline {
  color: #ccc;
  font-size: 28rpx;
}

/* 自定义开关 */
.custom-switch {
  margin: 20rpx;
  transform: scale(0.8);
  --active-color: #26c6da;
  position: absolute;
  top: -100rpx;
  left: 100rpx;
}

/* 添加设备卡片样式 */
.add-device-card .add-device-content {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
  width: 100%;
}

.add_icon_box {
    width: 100rpx;
    height: 100rpx;
    border-radius: 100rpx;
    border: 1px solid rgba(36, 204, 184, 1);
    text-align: center;
    line-height: 100rpx;
}

.add-text {
  width: 200rpx;
  margin-left: 30rpx;
  margin-top: 20rpx;
  font-size: 30rpx;
  color: #666;
}

/* 编辑按钮样式 */
.edit-button {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 8rpx;
}

/* 胶囊按钮样式 */
.capsule-button {
  --button-bg-color: #32c5d2;
  --button-text-color: white;
  --button-height: 40rpx;
  --button-width: 120rpx;
  --button-font-size: 24rpx;
  
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 999rpx;
  padding: 4rpx 12rpx;
  background-color: var(--button-bg-color);
  color: var(--button-text-color);
  font-size: var(--button-font-size);
  line-height: 1.33;
  height: var(--button-height);
  width: var(--button-width);
  font-weight: normal;
  box-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
  transition: all 0.2s ease;
  border: none;
  outline: none;
  cursor: pointer;

  &:active {
    transform: scale(0.98);
    box-shadow: 0 0.5rpx 1rpx rgba(0, 0, 0, 0.05);
  }
}

/* 操作按钮 */
.action-buttons {
  position: absolute;
  right: 5rpx;
  bottom: 20rpx;
  display: flex;
  gap: 20rpx;
}

/* 模态框表单样式 */
.modal-form {
  padding: 20rpx;
  
  .uni-forms-item {
    margin-bottom: 24rpx;
    
    .uni-forms-item__label {
      font-size: 28rpx;
      color: #666;
    }
    
    .uni-easyinput {
      border: 1rpx solid #eee;
      border-radius: 8rpx;
      padding: 12rpx;
    }
  }
}
</style>